const { findShop, insertShop, updateShop, removeShop} = require('../model/shop')

//获取商品
const getAllShop = (req,resp) =>{
    findShop().then(list =>{
        resp.json({
        code:200,
        body:{
            list
        }
        })
    }).catch(err =>{
        resp.json({
            code:400,
            body:{
                err
            }
        })
    })     
}

//新增一条商品
const addShop = (req,resp) =>{
    const {name, price, num} = req.query
    insertShop({name, price, num}).then(shop =>{
        resp.json({
            code:200,
            body:{
                msg:'新增成功！',
                shop
            }
        })
    }).catch(err =>{
        resp.json({
            code:400,
            body:{
                msg: '网络错误，请重试',
                err
            }
        })
    })
}

//修改一条商品
const editShop = (req,resp) =>{
    const {id, name, price, num} = req.query
    updateShop({id, name, price, num}).then(shop =>{
        resp.json({
            code:200,
            body:{
                msg:'修改成功！',
                shop
            }
        })
    }).catch(err =>{
        resp.json({
            code:400,
            body:{
                msg: '网络错误，请重试',
                err
            }
        })
    })
}

//删除一条商品
const deleteShop = (req,resp) =>{
    const { idx } = req.query
    removeShop({idx}).then(shop =>{
        resp.json({
            code:200,
            body:{
                msg:'修改成功！',
                shop
            }
        })
    }).catch(err =>{
        resp.json({
            code:400,
            body:{
                msg: '网络错误，请重试',
                err
            }
        })
    })
}

//暴露getAllShop
module.exports = {
    getAllShop,
    addShop,
    editShop,
    deleteShop
}